package com.datastructure.test.maxconsistofarray;

import java.util.*;
import java.util.stream.Collectors;

public class MaxConsistOfArray {

    public static void main(String[] args) {
        int[] data = {2,20,23,4,8};
        MaxConsistOfArray maxConsistOfArray = new MaxConsistOfArray();
        maxConsistOfArray.solve(data);
    }

    public String solve (int[] nums) {
        // write code here
        if(nums.length==1){
            return String.valueOf(nums[0]);
        }
        Map<Integer,Double> map = new HashMap<>();
        StringBuilder stringBuilder = new StringBuilder();
        int length = 0;
        for (int num : nums) {
            length = Math.max(length, String.valueOf(num).length());
        }
        for (int i = 0; i < nums.length; i++) {
            map.put(i,nums[i]*Math.pow(10,length-(String.valueOf(nums[i]).length())));
        }
        Double[] objects = map.values().toArray(new Double[0]);
        ArrayList<Double> list = new ArrayList<>();
        for (int i = objects.length-1; i >= 0; i--) {
            list.add(objects[i]);
        }
        List<Double> collect = list.stream().distinct().sorted(new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return o2.compareTo(o1);
            }
        }).collect(Collectors.toList());
        List<Integer> temp = new ArrayList<>();
        List<Integer> arrayList = new ArrayList<>();
        for (Double aDouble : collect) {
            temp.clear();
            arrayList.clear();
            double doubleTemp = aDouble;
            map.forEach((key, value) -> {
                if (value == doubleTemp) {
                    temp.add(key);
                }
            });
            for (Integer integer : temp) {
                arrayList.add(nums[integer]);
            }
            arrayList.stream().sorted().forEach(stringBuilder::append);
        }
        return String.valueOf(Long.valueOf(stringBuilder.toString()));
    }

    public String solve1 (int[] nums) {
        // write code here
        // 先将int数组转成String类型的集合，然后再按照前后相加的大小，从大到小排序
        List<String> list = Arrays.stream(nums).mapToObj(String::valueOf).sorted((k1,k2)->(k2+k1).compareTo(k1+k2)).collect(Collectors.toList());
        // 当第一个元素为0时直接返回“0”，否则将元素进行拼接成字符串。
        return "0".equals(list.get(0))?"0":String.join("",list);
    }
}
